window.onload = function() {
    const $ = name => document.querySelector(name);
    var teacherlogo = document.getElementById('teachercentre');
    var un = window.localStorage.getItem('username');
    var role6 = window.localStorage.getItem('role');
    if (role6 == 'teacher') {
        teacherlogo.style.display = 'block';
    }
    document.getElementById('userinfo').innerHTML = '用户名' + '&nbsp' + un;
    document.querySelector(".pic-wrap img").src = window.localStorage.getItem('avatar');
    document.querySelector(".pic img").src = window.localStorage.getItem('avatar');
    //关于cookie注销的函数
    function setCookie(_name, val, expires) {
        var d = new Date();
        d.setDate(d.getDate() + expires);
        document.cookie = _name + "=" + val + ";path=/;expires=" + d.toGMTString();
    }
    //退出登录，返回主页
    function Outlogin() {
        window.localStorage.removeItem("token");
        window.localStorage.removeItem('role');
        window.localStorage.removeItem('id');
        var obj = {};
        obj.name = '';
        obj.pass = '';
        var str = JSON.stringify(obj);
        setCookie("init", str, 0.000001);
    }

    //退出登录
    document.querySelector("#out-login").addEventListener('click', function() {
        Outlogin();
    })
    var token1 = window.localStorage.getItem('token');
    var rlogo = document.getElementById('rlogo');
    var userinfo = document.getElementById('userinfo');
    axios.defaults.timeout = 5500;
    axios.defaults.baseURL = 'http://120.24.80.83:3000';
    // axios.defaults.headers.common['Authorization'] = token1;
    axios.interceptors.request.use(function(config) {
        // 在发送请求之前做些什么
        // 若token存在， 则在每次请求头中加入token
        if (window.localStorage.getItem('token')) {
            config.headers.Authorization = window.localStorage.getItem('token');
            // axios.defaults.headers.common['Authorization'] = window.localStorage.getItem('token');
        }
        // console.log(config);
        return config;
    }, function(error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
    axios.interceptors.response.use(
            response => {
                if (getCookie("init")) {
                    var cookie = JSON.parse(getCookie("init"));
                } else {
                    var cookie = new Object();
                    var cookie = {
                        name: '',
                        pass: ''
                    };
                }
                if (response.data.msg == '登录失效' && (cookie.name == '' && cookie.pass == '')) {
                    // 这里写清除token的代码
                    // 清除token
                    console.log(response.data.msg);
                    setTimeout(() => {
                        // window.open('login.html');
                        rlogo.style.display = 'none';
                        userinfo.style.display = 'none';
                        userinfo.style.height = '0';
                    }, 3000);
                    // window.localStorage.removeItem('token');
                    console.log('登录过期，请重新登录');
                    $('.aftertips').innerHTML = '登录过期，请重新登录！';
                    errtip();
                    window.location.assign("/易动考核/拉勾教育/Homepage/index1.html");
                    Message({
                        message: '登录过期，请重新登录',
                        duration: 1000,
                        forbidClick: true
                    });
                    Message();
                    //window.location.href = 'index1.html';
                } else if ((response.data.code == 1 && (cookie.name != '' && cookie.pass != '')) || (response.data.code == 1 && (cookie.name == '' && cookie.pass == ''))) {
                    console.log('登录状态');
                    rlogo.style.display = 'block'
                    userinfo.style.display = 'block';
                }
                return response;
            },
            error => {
                if (error.response) {
                    switch (error.response.status) {
                        case 403:
                            // 这里写清除token的代码
                            console.log('清除token');
                            id1 = '';
                            Message({
                                message: '登录过期，请重新登录',
                                duration: 1000,
                                forbidClick: true
                            });
                            // 清除token
                            window.loaclStorage.removeItem('token');
                            // store.commit('loginSuccess', null);
                            // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
                            // setTimeout(() => {
                            //     router.replace({
                            //         path: '/login',
                            //         query: {
                            //             redirect: router.currentRoute.fullPath
                            //         }
                            //     });
                            // }, 1000);
                            break;
                    }
                }
                return Promise.reject(error.response.data)
            }
        )
        //页面加载时，如果有记录7天免登录
    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        if (cookie.name != '' && cookie.pass != '') {
            axios({
                    url: "/login",
                    method: "post",
                    data: {
                        "username": cookie.name,
                        "password": cookie.pass,
                    }
                })
                .then(function(response) {
                    console.log(response.data);
                    var res = response.data.data;
                    //使用loackstorge保存token，方便以后需要的时候用
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.username;
                    if (res.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res.avatar) {
                        document.querySelector(".pic img").src = res.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                        document.querySelector('.pic-wrap img').src = "img/register.png";
                    }
                })
        } else {
            console.log('cookie已注销');
            window.location.href = "index1.html";
        }
    }

    function getCookie(_name) {
        var cookie = document.cookie;
        var arr = cookie.split("; ");
        for (var i = 0; i < arr.length; i++) {
            var newArr = arr[i].split("=");
            if (newArr[0] == _name) {
                return newArr[1];
            }
        }
    }
    //验证token是否失效
    if (window.localStorage.getItem("token")) {
        axios({
            method: 'post',
            url: '/refresh',
        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                console.log('token有效');
                var id3 = window.localStorage.getItem('username');
                var role3 = window.localStorage.getItem('role');
                userinfo.style.display = 'block';
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + id3;
                if (role3 == 'teacher') {
                    teacherlogo.style.display = 'block';
                    document.getElementById('rolelogo').innerHTML = '教师';
                } else if (role3 == 'student') {
                    teacherlogo.style.display = 'none';
                    document.getElementById('rolelogo').innerHTML = '学生';
                }
                rlogo.style.display = 'block';
                if (window.localStorage.getItem('avatar')) {
                    document.querySelector(".pic img").src = window.localStorage.getItem('avatar');
                } else {
                    document.querySelector('#rlogo img').src = "img/register.png";
                    document.querySelector('.pic-wrap img').src = "img/register.png";
                }
            } else {
                console.log('error');
                // window.location.href = "index1.html";
                window.location.assign("/易动考核/拉勾教育/Homepage/index1.html");
            }

        }).catch(err => {

        })
    }
    var restmoney = '';
    var charge = document.querySelector('.chargebtn');
    var moneynum = document.querySelector('.money');
    var checkbtn = document.querySelector('.checkbtn');
    var cancelsbtn = document.querySelector('.cancelsbtn');
    //充值积分
    charge.onclick = function() {
            money1 = moneynum.value;
            axios({
                method: 'post',
                url: '/user/chargeMoney',
                data: {
                    money: money1
                }, //params是拼接参数请求，而data是把参数放进请求体

            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    console.log('获取成功');
                    document.getElementById('chargeresult').innerHTML = '充值成功';
                    $('.aftertips').innerHTML = res.msg;
                    successtip();
                    restmoney = res.data.money;
                    setTimeout(() => {
                        document.getElementById('chargeresult').innerHTML = '';
                        document.getElementById('money').value = '';
                    }, 1000);
                } else {
                    console.log('error');
                    document.getElementById('chargeresult').innerHTML = '充值失败，请重新尝试';
                    $('.aftertips').innerHTML = '充值失败';
                    errtip();
                    setTimeout(() => {
                        document.getElementById('chargeresult').innerHTML = '';
                        document.getElementById('money').value = '';
                    }, 1000);
                }

            })
        }
        //查询余额
    var moneynum1 = '0';
    checkbtn.onclick = function() {
        money1 = moneynum.value;
        axios({
            method: 'post',
            url: '/user/chargeMoney',
            data: {
                money: moneynum1
            }, //params是拼接参数请求，而data是把参数放进请求体

        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                console.log('获取成功');
                document.getElementById('chargeresult').innerHTML = '查询成功';
                $('.aftertips').innerHTML = '查询成功！';
                successtip();
                restmoney = res.data.money;
                document.getElementById('restmoney').innerHTML = '余额为：' + restmoney;
            } else {
                console.log('error');
            }

        })
    }

    cancelsbtn.onclick = function() {
            document.getElementById('money').value = '';

        }
        //上传头像
    var avatarupload = document.querySelector('.uploadbtn');
    avatarupload.onclick = function() {
            var file = document.getElementById("avatarupload");
            var formdata1 = new FormData();
            formdata1.append("avatar", file.files[0]);
            axios({
                    url: "/user/uploadAvatar",
                    method: "post",
                    data: formdata1,
                })
                .then(function(response) {
                    console.log(response.data);
                    $('.aftertips').innerHTML = response.data.msg;
                    successtip();
                    var avatarpic = response.data.data;
                    document.querySelector(".pic-wrap img").src = avatarpic.url;
                    document.querySelector(".pic img").src = avatarpic.url;
                    window.localStorage.setItem('avatar', avatarpic.url);
                }).catch(function(error) {
                    console.log(error);
                })
        }
        //更改用户名
    var clearname = document.querySelector('.clear');
    var newname = document.querySelector('.nickinput');
    var putnewname = document.querySelector('.update-info');
    clearname.onclick = function() {
        newname.value = '';
    }
    putnewname.onclick = function() {
            axios({
                method: 'post',
                url: '/user/changeUserName',
                data: {
                    username: newname.value
                }, //params是拼接参数请求，而data是把参数放进请求体

            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    console.log('修改成功');
                    $('.aftertips').innerHTML = '修改成功';
                    successtip();
                    document.getElementById('changeresult').innerHTML = '修改成功';
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + newname.value;
                    let name1 = newname.value;
                    let name2 = window.localStorage.getItem('password');
                    changecookie(name1, name2);
                    window.localStorage.removeItem('username');
                    window.localStorage.setItem('username', newname.value);
                } else if (res.code == -1) {
                    document.getElementById('changeresult').innerHTML = '该用户名已被使用';
                    console.log('error');
                }

            })
        }
        //修改密码
    var oldpass = document.getElementById('oldpass');
    var newpass = document.getElementById('newpass');
    var repeatpass = document.getElementById('repeatpass');
    oldpass.onblur = function() {
        if (oldpass.value != window.localStorage.getItem('password')) {
            document.getElementById('errortip').innerHTML = '与原密码不符合';
            setTimeout(() => {
                document.getElementById('errortip').innerHTML = '';
                document.getElementById('oldpass').value = '';
            }, 2000);

        }

    }
    repeatpass.onblur = function() {
        if (repeatpass.value != newpass.value) {
            document.getElementById('errortip').innerHTML = '与输入的新密码不符';
            document.getElementById('newpass').value = '';
            document.getElementById('repeatpass').value = '';
        }

    }
    var confirm = document.querySelector('.confirmbtn');
    var cancel = document.querySelector('.cancelbtn');
    confirm.addEventListener('click', function() {
        axios({
            method: 'post',
            url: '/user/changePass',
            data: {
                oldPassword: oldpass.value,
                newPassword: newpass.value
            }, //params是拼接参数请求，而data是把参数放进请求体

        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                document.getElementById('errortip').innerHTML = '修改成功！！';
                console.log('修改成功');
                $('.aftertips').innerHTML = '修改成功';
                successtip();
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + window.localStorage.getItem('username');
                let name2 = newpass.value;
                let name1 = window.localStorage.getItem('username');
                changecookie(name1, name2);
                window.localStorage.removeItem('password');
                window.localStorage.setItem('password', newpass.value);
            } else if (res.code == -1) {
                document.getElementById('errortip').innerHTML = '新密码与原密码不能相同';
                console.log('error');
            }

        })
    })
    cancel.addEventListener('click', function() {
            oldpass.value = '';
            newpass.value = '';
            repeatpass.value = '';
            document.getElementById('errortip').innerHTML = '';
        })
        //修改后修改cookie的值
    function changecookie(name1, name2) {
        var obj = {};
        obj.name = name1;
        obj.pass = name2;
        var str = JSON.stringify(obj);
        setCookie("init", str, 7);
    }

    function successtip() {
        var tips = $('.aftertips');
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#67c23a';
        console.log('成功');
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }

    //  操作失败后的提示信息
    function errtip() {
        var tips = $('.aftertips')
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#f02019';
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }
}